package com.example.javapracticaltraining.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.pojo.WorkRecord;
import com.example.javapracticaltraining.entity.pojo.MedicalStaff;
import com.example.javapracticaltraining.entity.pojo.StaffSchedule;
import com.example.javapracticaltraining.service.WorkRecordService;
import com.example.javapracticaltraining.service.MedicalStaffService;
import com.example.javapracticaltraining.service.StaffScheduleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 医护人员工作记录管理控制器
 */
@RestController
@RequestMapping("/workrecords")
@Tag(name = "工作记录管理", description = "医护人员工作记录的增删改查操作")
public class WorkRecordController {

    @Autowired
    private WorkRecordService workRecordService;

    @Autowired
    private MedicalStaffService medicalStaffService;

    @Autowired
    private StaffScheduleService staffScheduleService;

    /**
     * 获取所有工作记录
     * @return 工作记录列表
     */
    @Operation(summary = "获取所有工作记录", description = "返回系统中所有医护人员的工作记录列表")
    @ApiResponse(responseCode = "200", description = "成功获取工作记录列表")
    @GetMapping
    public R<List<WorkRecord>> getAllWorkRecords() {
        List<WorkRecord> records = workRecordService.list();
        return R.success(records);
    }

    /**
     * 分页获取工作记录
     * @param page 页码
     * @param pageSize 每页大小
     * @param staffId 医护人员ID（可选，用于筛选）
     * @param startTime 开始时间（可选，用于筛选）
     * @param endTime 结束时间（可选，用于筛选）
     * @return 分页后的工作记录列表
     */
    @Operation(summary = "分页获取工作记录", description = "根据条件分页查询工作记录，支持按医护人员ID和时间范围筛选")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取分页工作记录列表")
    })
    @GetMapping("/page")
    public R<Page<WorkRecord>> getWorkRecordsByPage(
            @Parameter(description = "页码，默认为1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页记录数，默认为10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "医护人员ID，可选参数") Integer staffId,
            @Parameter(description = "开始时间，可选参数，格式：yyyy-MM-ddTHH:mm:ss") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @Parameter(description = "结束时间，可选参数，格式：yyyy-MM-ddTHH:mm:ss") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {

        Page<WorkRecord> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<WorkRecord> queryWrapper = new LambdaQueryWrapper<>();

        if (staffId != null) {
            queryWrapper.eq(WorkRecord::getStaffId, staffId);
        }

        if (startTime != null) {
            queryWrapper.ge(WorkRecord::getStartTime, startTime);
        }

        if (endTime != null) {
            queryWrapper.le(WorkRecord::getEndTime, endTime);
        }

        // 默认按创建时间倒序排序
        queryWrapper.orderByDesc(WorkRecord::getCreateTime);

        workRecordService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据ID获取工作记录
     * @param recordId 记录ID
     * @return 工作记录信息
     */
    @GetMapping("/{recordId}")
    public R<WorkRecord> getWorkRecord(@PathVariable Integer recordId) {
        WorkRecord record = workRecordService.getById(recordId);
        if (record != null) {
            return R.success(record);
        }
        return R.failure(404, "未找到该工作记录");
    }

    /**
     * 获取指定医护人员的工作记录
     * @param staffId 医护人员ID
     * @return 工作记录列表
     */
    @GetMapping("/staff/{staffId}")
    public R<List<WorkRecord>> getWorkRecordsByStaff(@PathVariable Integer staffId) {
        // 检查医护人员是否存在
        MedicalStaff staff = medicalStaffService.getById(staffId);
        if (staff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        LambdaQueryWrapper<WorkRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkRecord::getStaffId, staffId)
                   .orderByDesc(WorkRecord::getCreateTime);

        List<WorkRecord> records = workRecordService.list(queryWrapper);
        return R.success(records);
    }

    /**
     * 获取指定排班的工作记录
     * @param scheduleId 排班ID
     * @return 工作记录列表
     */
    @GetMapping("/schedule/{scheduleId}")
    public R<List<WorkRecord>> getWorkRecordsBySchedule(@PathVariable Integer scheduleId) {
        // 检查排班是否存在
        StaffSchedule schedule = staffScheduleService.getById(scheduleId);
        if (schedule == null) {
            return R.failure(404, "未找到该排班记录");
        }

        LambdaQueryWrapper<WorkRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkRecord::getScheduleId, scheduleId)
                   .orderByDesc(WorkRecord::getCreateTime);

        List<WorkRecord> records = workRecordService.list(queryWrapper);
        return R.success(records);
    }

    /**
     * 添加新的工作记录
     * @param record 工作记录信息
     * @return 操作结果
     */
    @Operation(summary = "添加工作记录", description = "创建新的医护人员工作记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "工作记录添加成功"),
        @ApiResponse(responseCode = "404", description = "未找到相关医护人员或排班记录"),
        @ApiResponse(responseCode = "400", description = "排班记录与医护人员不匹配")
    })
    @PostMapping
    public R<String> addWorkRecord(@RequestBody WorkRecord record) {
        // 检查医护人员是否存在
        MedicalStaff staff = medicalStaffService.getById(record.getStaffId());
        if (staff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        // 如果提供了排班ID，检查排班是否存在
        if (record.getScheduleId() != null) {
            StaffSchedule schedule = staffScheduleService.getById(record.getScheduleId());
            if (schedule == null) {
                return R.failure(404, "未找到该排班记录");
            }

            // 检查排班与医护人员是否匹配
            if (!schedule.getStaffId().equals(record.getStaffId())) {
                return R.failure(400, "排班记录与医护人员不匹配");
            }
        }

        // 设置创建时间
        record.setCreateTime(LocalDateTime.now());

        workRecordService.save(record);
        return R.success("工作记录添加成功");
    }

    /**
     * 更新工作记录信息
     * @param record 工作记录信息
     * @return 操作结果
     */
    @Operation(summary = "更新工作记录", description = "根据ID更新医护人员工作记录信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "工作记录更新成功"),
        @ApiResponse(responseCode = "400", description = "工作记录ID不能为空或排班记录与医护人员不匹配"),
        @ApiResponse(responseCode = "404", description = "未找到相关工作记录、医护人员或排班记录")
    })
    @PutMapping
    public R<String> updateWorkRecord(@RequestBody WorkRecord record) {
        // 检查是否存在
        if (record.getRecordId() == null) {
            return R.failure(400, "工作记录ID不能为空");
        }

        WorkRecord existingRecord = workRecordService.getById(record.getRecordId());
        if (existingRecord == null) {
            return R.failure(404, "未找到该工作记录");
        }

        // 检查医护人员是否存在
        MedicalStaff staff = medicalStaffService.getById(record.getStaffId());
        if (staff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        // 如果提供了排班ID，检查排班是否存在
        if (record.getScheduleId() != null) {
            StaffSchedule schedule = staffScheduleService.getById(record.getScheduleId());
            if (schedule == null) {
                return R.failure(404, "未找到该排班记录");
            }

            // 检查排班与医护人员是否匹配
            if (!schedule.getStaffId().equals(record.getStaffId())) {
                return R.failure(400, "排班记录与医护人员不匹配");
            }
        }

        // 保留原创建时间
        record.setCreateTime(existingRecord.getCreateTime());

        workRecordService.updateById(record);
        return R.success("工作记录更新成功");
    }

    /**
     * 删除工作记录
     * @param recordId 工作记录ID
     * @return 操作结果
     */
    @Operation(summary = "删除工作记录", description = "根据ID删除医护人员工作记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "工作记录删除成功"),
        @ApiResponse(responseCode = "404", description = "未找到相关工作记录")
    })
    @DeleteMapping("/{recordId}")
    public R<String> deleteWorkRecord(@Parameter(description = "工作记录ID") @PathVariable Integer recordId) {
        // 检查是否存在
        WorkRecord existingRecord = workRecordService.getById(recordId);
        if (existingRecord == null) {
            return R.failure(404, "未找到该工作记录");
        }

        // 执行删除操作
        workRecordService.removeById(recordId);
        return R.success("工作记录删除成功");
    }

    /**
     * 批量添加工作记录
     * @param records 工作记录列表
     * @return 操作结果
     */
    @Operation(summary = "批量添加工作记录", description = "一次性创建多条医护人员工作记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "批量添加工作记录成功"),
        @ApiResponse(responseCode = "400", description = "工作记录列表不能为空")
    })
    @PostMapping("/batch")
    public R<String> addWorkRecordsBatch(@RequestBody List<WorkRecord> records) {
        if (records == null || records.isEmpty()) {
            return R.failure(400, "工作记录列表不能为空");
        }

        // 设置创建时间
        LocalDateTime now = LocalDateTime.now();
        for (WorkRecord record : records) {
            record.setCreateTime(now);
        }

        workRecordService.saveBatch(records);
        return R.success("批量添加工作记录成功");
    }
}
